(function () {
    app
        .controller('signalCtrl', ['$rootScope', '$scope', 'RESTService', '$timeout', '$uibModal', function ($rootScope, $scope, RESTService, $timeout, $uibModal) {
            $rootScope.selecInd = 2;
            $rootScope.showTabs = true;
            $scope.$on("$destroy", function () {
                $rootScope.showTabs = false;
            });
            $scope.$on('childMsgs', function (e, d) {
                $scope.msgs.push(d);
                RESTService.postResponse('/rest/chatmessage/setReadFlag?').then(function (response) {
                    console.log($scope.count);
                });
            });

            $scope.status = 'all';
            var loadData = function () {
                RESTService.getResponse('/rest/chatmessage/getChatMessages?mode=' + $scope.status).then(function (response) {
                    $scope.$emit('parStatus', $scope.status);
                    $scope.msgs = response.data;
                    $timeout(function () {
                        $(document).scrollTop($('.msgslist')[0].scrollHeight);
                    }, 59);
                    RESTService.postResponse('/rest/chatmessage/setReadFlag?').then(function (response) {
                        $scope.$parent.$parent.count = 0;
                    });
                });
            };
            loadData();

            $scope.btnMode = function (newMode) {
                $scope.status = newMode;
                loadData();
            };

            $scope.clearMsgs = function () {
                RESTService.postResponse('/rest/chatmessage/clearChatMessage?').then(function (response) {
                    $scope.msgs = {};
                    $('.clearMsgs').modal('hide');
                    console.log('消息已清除');
                });
            };

            //打开模态框
            $scope.openSignalModal = function (data) {
                $uibModal.open(angular.extend({
                    templateUrl: 'signalModal.html',
                    controller: 'signalModalCtrl',
                    resolve: {
                        info: function () {
                            return data;
                        }
                    }
                }));
            }
        }])
        .controller('signalModalCtrl', ['$scope', 'info', '$uibModalInstance', 'RESTService', function ($scope, info, $uibModalInstance, RESTService) {
            $scope.data = info;
            console.log('data:==========', $scope.data);
            $scope.close = function () {
                $uibModalInstance.close();
            };

            RESTService.getResponse('/rest/signal/getSignal?signalId=' + $scope.data.uri).then(function (res) {
                $scope.signalData = res.data[0];
                console.log(res.data);
                RESTService.getResponse('/rest/candle/getCandlesBySignal?signalId=' + $scope.data.uri)
                    .then(function (res) {
                        console.log(res);
                        // $scope.assessDetails = res;
                        drawCandle(res.data);
                    });
            });

            function drawCandle(myData) {
                // console.log(myData);
                // 基于准备好的dom，初始化echarts实例
                var myChart = echarts.init($('#main')[0]);

                function calculateMA(dayCount, data) {
                    var result = [];
                    for (var i = 0, len = data.length; i < len; i++) {
                        if (i < dayCount) {
                            result.push('-');
                            continue;
                        }
                        var sum = 0;
                        for (var j = 0; j < dayCount; j++) {
                            sum += data[i - j][1];
                        }
                        result.push(sum / dayCount);
                    }
                    return result;
                }


                // 时间
                var dates = myData.map(function (item) {
                    return item.updatedShow;
                });

                // 数据
                var data = myData.map(function (item) {
                    return [+item.open, +item.close, +item.low, +item.high, +item.changing + '%'];
                });

                // 标记
                var getMarkpoints = function (arr) {
                    var markPoints = [];
                    for (var i = 0; i < arr.length; i++) {
                        if (arr[i].mark !== null) {
                            markPoints.push({
                                name: arr[i].mark,
                                coord: [arr[i].updatedShow, arr[i].highask],
                                value: arr[i].mark,
                                itemStyle: {
                                    normal: {color: (arr[i].mark === 'B' ? 'green' : 'red')}
                                }
                            });
                        }
                    }
                    return markPoints;
                };


                // 配置项
                var option = {
                    title: {
                        text: $scope.data.instrument,
                        textStyle: {
                            color:'#fff',
                            fontSize:'10px'
                        }

                    },
                    backgroundColor: '#21202D',
                    legend: {
                        data: ['K线', 'MA3', 'MA5'],
                        inactiveColor: '#777',
                        textStyle: {
                            color: '#fff'
                        }
                    },
                    grid:{
                        left:'10%',
                        right:'20%',
                        bottom:'15%'
                    },
                    tooltip: {
                        trigger: 'axis',
                        transitionDuration: 0.4,
                        axisPointer: {
                            animation: true,
                            type: 'cross',
                            lineStyle: {
                                color: '#376df4',
                                width: 2,
                                opacity: 1
                            }
                        }
                    },
                    xAxis: {
                        type: 'category',
                        data: dates,
                        axisLine: {lineStyle: {color: '#8392A5'}}
                    },
                    yAxis: {
                        scale: true,
                        axisLine: {lineStyle: {color: '#8392A5'}},
                        splitLine: {show: false}
                    },
                    dataZoom: [{
                        textStyle: {
                            color: '#8392A5'
                        },
                        handleIcon: 'M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4v1.3h1.3v-1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z',
                        handleSize: '80%',
                        dataBackground: {
                            areaStyle: {
                                color: '#8392A5'
                            },
                            lineStyle: {
                                opacity: 0.8,
                                color: '#8392A5'
                            }
                        },
                        handleStyle: {
                            color: '#fff',
                            shadowBlur: 3,
                            shadowColor: 'rgba(0, 0, 0, 0.6)',
                            shadowOffsetX: 2,
                            shadowOffsetY: 2
                        }
                    }, {
                        type: 'inside'
                    }],
                    animation: false,
                    series: [
                        {
                            type: 'candlestick',
                            name: 'K线',
                            data: data,
                            itemStyle: {
                                normal: {
                                    color: '#FD1050',
                                    color0: '#0CF49B',
                                    borderColor: '#FD1050',
                                    borderColor0: '#0CF49B'
                                }
                            },
                            markPoint: {
                                label: {
                                    normal: {
                                        formatter: function (param) {
                                            return param.value;
                                        }
                                    }
                                },
                                data: getMarkpoints(myData)
                            },
                            markLine: {
                                symbol: ['none', 'none'],
                                precision: 5,
                                data: [
                                    // [
                                    //     {
                                    //         name: 'from lowest to highest',
                                    //         type: 'min',
                                    //         valueDim: 'lowest',
                                    //         symbol: 'circle',
                                    //         symbolSize: 10,
                                    //         label: {
                                    //             normal: {show: false},
                                    //             emphasis: {show: false}
                                    //         }
                                    //     },
                                    //     {
                                    //         type: 'max',
                                    //         valueDim: 'highest',
                                    //         symbol: 'circle',
                                    //         symbolSize: 10,
                                    //         label: {
                                    //             normal: {show: false},
                                    //             emphasis: {show: false}
                                    //         }
                                    //     }
                                    // ],
                                    {
                                        name: 'stopLoss',
                                        yAxis: $scope.signalData.stopLoss,
                                        itemStyle:{
                                            normal:{color:'red'}
                                        }
                                    },
                                    {
                                        name: 'takePerfit1,',
                                        yAxis: $scope.signalData.takePerfit1,
                                        itemStyle:{
                                            normal:{color:'green'}
                                        }
                                    },
                                    {
                                        name: 'price',
                                        yAxis: $scope.signalData.price,
                                        itemStyle:{
                                            normal:{color:'blue'}
                                        }
                                    }
                                ]
                            }
                        },
                        {
                            name: 'MA3',
                            type: 'line',
                            data: calculateMA(3, data),
                            smooth: true,
                            showSymbol: false,
                            lineStyle: {
                                normal: {
                                    width: 1
                                }
                            },
                            tooltip:{
                                show:false
                            }
                        },
                        {
                            name: 'MA5',
                            type: 'line',
                            data: calculateMA(5, data),
                            smooth: true,
                            showSymbol: false,
                            lineStyle: {
                                normal: {
                                    width: 1
                                }
                            },
                            tooltip:{
                                show:false
                            }
                        }
                    ]
                };

                // 使用刚指定的配置项和数据显示图表。
                myChart.setOption(option);
            }

        }]);
})();
